package com.mdlib.helper.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;

import com.hn.plt.config.ClientConfig;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.api.service.WXApi;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.WXEvent;
import com.mdlib.helper.model.entity.AuthEntity;
import com.mdlib.helper.model.entity.AuthUser;
import com.mdlib.helper.model.entity.WXUser;
import com.mdlib.helper.utils.IsInstall;
import com.mdlib.helper.utils.ToastUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.mdlib.helper.utils.ToastUtil.showToast;

/**
 * Created by librabin on 16/10/22.
 */

public abstract class BaseAuthFragment extends BaseAppFragmentV2 {

    protected abstract void featchAutherSucc(AuthUser authUser);
    protected abstract void featchAutherFail(String msg);


    private LocalBroadcastManager mLocalBroadcastManager;

    private Tencent mTencent;

    private IWXAPI mWXApi;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver();
        mWXApi = WXAPIFactory.createWXAPI(mActivity.getApplicationContext(), ClientConfig.WX_APP_ID, true);
        mWXApi.registerApp(ClientConfig.WX_APP_ID);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }


    protected void doWXAuth() {
        if (IsInstall.isWeixinAvilible(mActivity)) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "md_helper";
            mWXApi.sendReq(req);
        } else {
            ToastUtil.showToast(mActivity.getResources().getString(R.string.general_wx_install));
        }
    }

    protected void doQQAuth() {
        if (IsInstall.isQQClientAvailable(mActivity)) {
            mTencent = Tencent.createInstance(ClientConfig.QQ_APP_ID, mActivity.getApplicationContext());
//            if (!mTencent.isSessionValid()) {
            mTencent.login(mActivity, "all", mQQLoginListener);
//            }
        } else {
            showToast(mActivity.getResources().getString(R.string.general_qq_install));
        }
    }

    protected void getQQTencent() {

    }


    private void featchQQInfo(Context context, Tencent tencent, JSONObject jsonObject) {
        try {
            String accessToken = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            final String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            tencent.setAccessToken(accessToken, expires);
            tencent.setOpenId(openId);

            UserInfo userInfo = new UserInfo(context, tencent.getQQToken());
            userInfo.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {
                    JSONObject result = (JSONObject) o;
                    AuthEntity authEntity = new AuthEntity();
                    authEntity.setType("qq");
                    authEntity.setUid(openId);
                    try {
                        AuthUser authUser = new AuthUser(MDConstant.AUTH_TYPE_QQ,
                                openId,
                                result.getString("nickname"),
                                result.getString("figureurl_qq_2"),
                                ""
                                );
                        featchAutherSucc(authUser);

                    } catch (Exception e) {
                        featchAutherFail("获取用户信息失败");
                    }
                }

                @Override
                public void onError(UiError uiError) {
                    featchAutherFail("获取用户信息失败");
                }

                @Override
                public void onCancel() {
                    featchAutherFail("获取用户信息取消");
                }
            });


        } catch (Exception e) {
            featchAutherFail("异常错误");
        }


    }


    private void featchWXInfo(String code) {
        final WXApi wxApi = DataManager.getInstance().getWXApi();
        addSubscribe(wxApi.getWXToken(ClientConfig.WX_APP_ID,
                ClientConfig.WX_APP_SECRET, code, "authorization_code")
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<WXUser, Observable<WXUser>>() {
                    @Override
                    public Observable<WXUser> call(WXUser wxUser) {
                        return wxApi.getWXUserInfo(wxUser.getAccessToken(), wxUser.getOpenId());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribe<WXUser>() {
                    @Override
                    protected void onSucc(WXUser wxUser) {
                        AuthUser authUser = new AuthUser(MDConstant.AUTH_TYPE_WX,
                                wxUser.getUid(),
                                wxUser.getNickName(),
                                wxUser.getAvatar(),
                                ""
                        );
                        featchAutherSucc(authUser);
                    }

                    @Override
                    protected void onFail(String msg) {
                        featchAutherFail(msg);
                    }
                }));
    }





    private IUiListener mQQLoginListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            featchQQInfo(mActivity, mTencent, (JSONObject) o);
        }

        @Override
        public void onError(UiError uiError) {
            featchAutherFail("授权失败");
        }

        @Override
        public void onCancel() {
            featchAutherFail("用户取消");
        }
    };



    private void registerReceiver() {
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MDConstant.ACTION_AUTH_INFO);
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void unregisterReceiver() {
        mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
    }



    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MDConstant.ACTION_AUTH_INFO)) {
                WXEvent wxEvent = (WXEvent) intent.getSerializableExtra(MDConstant.EVENT_AUTH_WX);
//                Logger.e(wxEvent.toString());
                if (wxEvent.code == MDConstant.STATE_SUCC) {
                    featchWXInfo(wxEvent.wxCode);
                } else {
                    featchAutherFail(wxEvent.msg);
                }
            }
        }
    };




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, mQQLoginListener);
    }








}
